/**
 * 
 */
package com.study.concurrency;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.TimeUnit;


/**
 * @author Administrator
 * @date 2019年6月19日
 */
public class BlockingDequeTest {

	public static void main(String[] args) {
		ArrayBlockingQueue<String> list = new ArrayBlockingQueue<String>(3);
		new Thread(new AddTask1(list)).start();
		
		new Thread(new RemoveTask1(list)).start();
	}
}

class AddTask1 implements Runnable{
	private ArrayBlockingQueue<String> list;
	
	public AddTask1(ArrayBlockingQueue<String> list1){
		this.list = list1;
	}

	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		for(int i = 0; i < 10; i++){
			try {
				Thread.sleep(new Random().nextInt(2000));
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				//add(), offer() 各有不同
				list.put(Thread.currentThread().getName() + i);  //当队列满时，存储元素的线程会等待队列可用。
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

class RemoveTask1 implements Runnable{
	private ArrayBlockingQueue<String> list;
	
	public RemoveTask1(ArrayBlockingQueue<String> list1){
		this.list = list1;
	}

	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		for(int i = 0; i < 10; i++){
			try {
				try {
					Thread.sleep(new Random().nextInt(2000));
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("消费：" + list.take()); //在队列为空时，获取元素的线程会等待队列变为非空。
				//System.out.println("消费：" + list.take());
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}